package com.promise.paging

import android.arch.lifecycle.Transformations
import android.arch.paging.LivePagedListBuilder
import java.util.concurrent.Executor

/**
 * Created by CQNNJ-003 on 2018/6/8.
 */
class UserPostRepository(private val redditApi: Api,private val networkExecutor: Executor) : PostRepository {

    override fun posts(pageSize: Int): Listing<QuestsData> {
        val sourceFactory = UserDataSourceFactory(
                redditApi = redditApi,
                retryExecutor = networkExecutor
        )

        val livePagedList = LivePagedListBuilder(sourceFactory, pageSize)
                // provide custom executor for network requests, otherwise it will default to
                // Arch Components' IO pool which is also used for disk access
                .setFetchExecutor(networkExecutor)
                .build()
        val refreshState = Transformations.switchMap(sourceFactory.sourceLiveData) {
            it.initialLoad
        }

        return Listing(
                pagedList = livePagedList,
//                networkState = Transformations.switchMap(sourceFactory.sourceLiveData, {
//                    it.networkState
//                }),
                retry = {
                    sourceFactory.sourceLiveData.value?.retryAllFailed()
                },
                refresh = {
                    sourceFactory.sourceLiveData.value?.invalidate()
                },
                refreshState = refreshState
        )
    }
}